{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 市场微观结构分析\n",
    "\n",
    "本笔记本实现市场微观结构相关分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import akshare as ak\n",
    "\n",
    "# 设置中文显示\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "plt.rcParams['axes.unicode_minus'] = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 订单簿分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def analyze_order_book(symbol):\n",
    "    \"\"\"\n",
    "    分析股票订单簿\n",
    "    \n",
    "    Args:\n",
    "        symbol: 股票代码\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # 获取实时订单簿数据\n",
    "        order_book = ak.stock_zh_a_quote(symbol=symbol)\n",
    "        \n",
    "        # 计算买卖价差\n",
    "        bid_ask_spread = order_book['ask1'] - order_book['bid1']\n",
    "        \n",
    "        # 计算市场深度\n",
    "        bid_depth = order_book['bid_volume1'] + order_book['bid_volume2'] + order_book['bid_volume3']\n",
    "        ask_depth = order_book['ask_volume1'] + order_book['ask_volume2'] + order_book['ask_volume3']\n",
    "        \n",
    "        return {\n",
    "            'bid_ask_spread': bid_ask_spread,\n",
    "            'bid_depth': bid_depth,\n",
    "            'ask_depth': ask_depth\n",
    "        }\n",
    "    except Exception as e:\n",
    "        print(f\"订单簿分析失败: {e}\")\n",
    "        return None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 流动性分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def liquidity_analysis(symbol, days=30):\n",
    "    \"\"\"\n",
    "    股票流动性分析\n",
    "    \n",
    "    Args:\n",
    "        symbol: 股票代码\n",
    "        days: 分析天数\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # 获取历史数据\n",
    "        df = ak.stock_zh_a_hist(symbol=symbol, period=\"daily\", adjust=\"qfq\")\n",
    "        df = df.tail(days)\n",
    "        \n",
    "        # 计算流动性指标\n",
    "        turnover = df['turnover'].mean()  # 平均换手率\n",
    "        volume = df['volume'].mean()  # 平均成交量\n",
    "        \n",
    "        # 计算Amihud非流动性指标\n",
    "        returns = df['close'].pct_change()\n",
    "        amihud = (abs(returns) / df['volume']).mean()\n",
    "        \n",
    "        return {\n",
    "            'turnover': turnover,\n",
    "            'volume': volume,\n",
    "            'amihud_illiquidity': amihud\n",
    "        }\n",
    "    except Exception as e:\n",
    "        print(f\"流动性分析失败: {e}\")\n",
    "        return None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 主分析流程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例分析\n",
    "symbol = '600519'  # 贵州茅台\n",
    "\n",
    "# 订单簿分析\n",
    "order_book_metrics = analyze_order_book(symbol)\n",
    "print(\"订单簿分析结果:\")\n",
    "print(f\"买卖价差: {order_book_metrics['bid_ask_spread']:.2f}\")\n",
    "print(f\"买盘深度: {order_book_metrics['bid_depth']}\")\n",
    "print(f\"卖盘深度: {order_book_metrics['ask_depth']}\")\n",
    "\n",
    "# 流动性分析\n",
    "liquidity_metrics = liquidity_analysis(symbol)\n",
    "print(\"\\n流动性分析结果:\")\n",
    "print(f\"平均换手率: {liquidity_metrics['turnover']:.4f}\")\n",
    "print(f\"平均成交量: {liquidity_metrics['volume']}\")\n",
    "print(f\"Amihud非流动性指标: {liquidity_metrics['amihud_illiquidity']:.6f}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}